using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using LuaInterface;
using Vuplex.WebView;

public class WebViewEx : MonoBehaviour
{
    Vuplex.WebView.CanvasWebViewPrefab browser;

    public GameObject[] data_arr;

    public RectTransform close_rect;

    // 1用来传入url


    // Start is called before the first frame update
    void Start()
    {

      //  SetBtnPos(0, 0);

    }



    public async void LoadUrl(string url)
    {

        browser = GetComponent<Vuplex.WebView.CanvasWebViewPrefab>();
        await Task.WhenAll(new Task[] {
               browser.WaitUntilInitialized()
            });

        browser.WebView.LoadUrl(url);
        // Web.ClearAllData();//清理缓存
        // Web.SetIgnoreCertificateErrors(true);//证书错误忽略

        browser = GetComponent<Vuplex.WebView.CanvasWebViewPrefab>();
        browser.WebView.UrlChanged += (sender, eventArgs) =>
        {
            data_arr[0].gameObject.name = eventArgs.Url;
            Debug.Log("[CanvasWebViewDemo] URL changed: " + eventArgs.Url);
            urlChanged();
        };
    }

    public void SetAudioMuted(bool muted)
    {
        var mutableWebView = browser.WebView as Vuplex.WebView.IWithMutableAudio;
        if (mutableWebView != null)
        {
            mutableWebView.SetAudioMuted(muted);
        }
    }

    public void ReturnHall()
    {
  
        if (LuaMgr.GetMainState() != null)
        {
            LuaFunction func = LuaMgr.GetMainState().GetFunction("ScriptToLua.ScriptToLua.returnHall");
            if (func != null)
            {
                func.BeginPCall();
                func.PCall();
                func.EndPCall();
                func.Dispose();
            }
        }
    }

    public void SetBtnPos(string s)
    {
        // 用_切割字符串
        string[] values = s.Split('_');
        
        // 尝试将字符串转换为float
        close_rect.anchorMin = new Vector2(float.Parse(values[0]), float.Parse(values[1]));
        close_rect.anchorMax = new Vector2(float.Parse(values[2]), float.Parse(values[3]));
        close_rect.pivot = new Vector2(float.Parse(values[4]), float.Parse(values[5]));
        close_rect.localEulerAngles = new Vector3(float.Parse(values[6]), float.Parse(values[7]), float.Parse(values[8]));
        close_rect.anchoredPosition = new Vector2(float.Parse(values[9]), float.Parse(values[10]));
       
    }
    public void urlChanged()
    {
        if (LuaMgr.GetMainState() != null)
        {
            LuaFunction func = LuaMgr.GetMainState().GetFunction("ScriptToLua.ScriptToLua.urlChanged");
            if (func != null)
            {
                func.BeginPCall();
                func.PCall();
                func.EndPCall();
                func.Dispose();
            }
        }
    }

}
